package com.geostar.constructionland.statistics.service.factory;

import com.geostar.constructionland.common.enums.ResultType;
import com.geostar.constructionland.statistics.mapping.QueryMappedStatement;
import com.geostar.constructionland.statistics.mapping.ResultTypeStatement;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author makoto_zhu
 * @Date 2020-11-18 05:25:44
 * @Description
 **/
@Component
public class PostDataProcessFactory {
    // 后置数据处理(后续可以改成责任链模式)
    public void process(QueryMappedStatement statement, List<Map<String, Object>> result) {
        ResultTypeStatement resultTypeStatement = statement.getResultTypeStatement();

        Integer percision = resultTypeStatement.getPrecision();
        // 精度处理
        percision = percision == null ? 0 : percision;
        for (Map<String, Object> map : result) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Object value = entry.getValue();
                if (value instanceof Integer || value instanceof BigDecimal || value instanceof Long) {
                    value = new BigDecimal(String.valueOf(value)).setScale(percision, RoundingMode.HALF_UP).toString();
                }
                map.put(entry.getKey(), value);
            }
        }

        replaceHtmlTemplate(statement, result);
    }

    // 如果配置为返回html将根据html模板进行替换
    public void replaceHtmlTemplate(QueryMappedStatement statement, List<Map<String, Object>> result) {
        String htmlTemplate = statement.getResultTypeStatement().getHtmlTemplate();
        if (Objects.equals(statement.getResultTypeStatement().getResultType(), ResultType.HTML)) {
            for (Map<String, Object> subMap : result) {
                for (Map.Entry<String, Object> entry : subMap.entrySet()) {
                    htmlTemplate = htmlTemplate.replace("{"+entry.getKey()+"}",entry.getValue().toString());
                }
            }


            // 去除所有换行
            htmlTemplate = htmlTemplate.replaceAll("\r\n|\r|\n", "");
            // 重新组装结果集
            result.clear();
            Map<String,Object> map = new HashMap<>();
            map.put("HTML",htmlTemplate);
            result.add(map);
        }
    }
}
